package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
)

func download(url, fileName string) {
	response, err := http.Get(url)
	if err != nil {
		fmt.Printf("请求失败，err-->%v", err)
		return
	}
	file, err := os.Create(fileName)
	if err != nil {
		fmt.Printf("创建文件失败，err-->%v", err)
		return
	}
	defer func() {
		response.Body.Close()
		file.Close()
	}()
	io.Copy(file, response.Body)
}

type Reader struct {
	io.Reader
	totalBytes int64
	curBytes   int64
}

func (r *Reader) Read(p []byte) (n int, err error) {
	n, err = r.Reader.Read(p)
	if err != nil {
		return
	}
	r.curBytes += int64(n)
	// %%输出效果是：%
	// \r是打印后，下次打印不换行，而是从头开始
	fmt.Printf("\r下载进度:%v%%", r.curBytes*100/r.totalBytes)
	return

}

func downloadWiteProgress(url, fileName string) {
	response, err := http.Get(url)
	if err != nil {
		fmt.Printf("请求失败，err-->%v", err)
		return
	}
	file, err := os.Create(fileName)
	if err != nil {
		fmt.Printf("创建文件失败，err-->%v", err)
		return
	}
	customReader := &Reader{
		Reader:     response.Body,
		totalBytes: response.ContentLength,
	}
	defer func() {
		response.Body.Close()
		file.Close()
	}()
	io.Copy(file, customReader)
}

func main() {
	//download("https://heyingjiee.github.io/logo.png", "avatar.png")
	downloadWiteProgress("https://heyingjiee.github.io/logo.png", "avatar.png")
}
